<!-- 个人资料 -->
<template>
  <view class="profile-page">
    <!-- 头像区域 -->
    <view class="avatar-section">
      <view class="avatar-container" @click="onChangeAvatar">
        <image 
          class="avatar-image" 
          :src="state.model?.avatar || sheep.$url.static('/static/img/shop/default_avatar.png')"
          mode="aspectFill"
        />
        <view class="camera-icon">
          <image class="camera-image" src="/static/photo.png" mode="aspectFit" />
        </view>
      </view>
      <text class="upload-hint">点击上传头像</text>
    </view>

    <!-- 个人信息卡片 -->
    <view class="info-card">
      <view class="info-item" @click="editNickname">
        <text class="info-label">用户昵称</text>
        <view class="info-content">
          <text class="info-value">{{ state.model?.nickname || '未设置' }}</text>
          <text class="arrow-icon">›</text>
        </view>
      </view>
      
      <view class="info-item">
        <text class="info-label">手机号码</text>
        <view class="info-content">
          <text class="info-value">{{ userInfo.mobile || '未绑定' }}</text>
        </view>
      </view>
      
      <view class="info-item" @click="editGender">
        <text class="info-label">性别</text>
        <view class="info-content">
          <text class="info-value">{{ getGenderText(state.model?.sex) }}</text>
          <text class="arrow-icon">›</text>
        </view>
      </view>
    </view>

    <!-- 修改昵称弹框 -->
    <view class="nickname-modal" v-if="state.showNicknameModal" @click="closeNicknameModal">
      <view class="modal-content" @click.stop>
        <view class="modal-header">
          <text class="modal-title">修改昵称</text>
          <view class="modal-close" @click="closeNicknameModal">×</view>
        </view>
        <view class="modal-body">
          <input 
            class="nickname-input" 
            v-model="state.nicknameInput" 
            type="text" 
            placeholder="请输入昵称" 
            maxlength="20"
            :focus="state.showNicknameModal"
          />
        </view>
        <view class="modal-footer">
          <view class="modal-btn cancel-btn" @click="closeNicknameModal">取消</view>
          <view class="modal-btn confirm-btn" @click="confirmNickname">确定</view>
        </view>
      </view>
    </view>

  </view>
</template>

<script setup>
  import { computed, reactive, onBeforeMount } from 'vue';
  import sheep from '@/sheep';
  import { clone } from 'lodash-es';
  import { showAuthModal } from '@/sheep/hooks/useModal';
  import UserApi from '@/sheep/api/member/user';
  import {
    chooseAndUploadFile,
    uploadFilesFromPath,
  } from '@/sheep/components/s-uploader/choose-and-upload-file';

  const state = reactive({
    model: {}, // 个人信息
    rules: {},
    thirdInfo: {}, // 社交用户的信息
    showNicknameModal: false, // 显示修改昵称弹框
    nicknameInput: '', // 昵称输入框值
  });

  const sexRadioMap = [
    {
      name: '男',
      value: '1',
    },
    {
      name: '女',
      value: '2',
    },
  ];

  const userInfo = computed(() => sheep.$store('user').userInfo);

  // 获取性别文本
  const getGenderText = (sex) => {
    if (sex === 1) return '男';
    if (sex === 2) return '女';
    return '未设置';
  };

  // 编辑昵称
  const editNickname = () => {
    state.nicknameInput = state.model?.nickname || '';
    state.showNicknameModal = true;
  };

  // 关闭昵称弹框
  const closeNicknameModal = () => {
    state.showNicknameModal = false;
    state.nicknameInput = '';
  };

  // 确认修改昵称
  const confirmNickname = async () => {
    if (!state.nicknameInput || state.nicknameInput.trim() === '') {
      uni.showToast({
        title: '昵称不能为空',
        icon: 'none'
      });
      return;
    }
    if (state.nicknameInput.trim().length > 20) {
      uni.showToast({
        title: '昵称不能超过20个字符',
        icon: 'none'
      });
      return;
    }
    state.model.nickname = state.nicknameInput.trim();
    state.showNicknameModal = false;
    await saveUserInfo();
    state.nicknameInput = '';
  };

  // 编辑手机号
  const editMobile = () => {
    showAuthModal('changeMobile');
  };

  // 编辑性别
  const editGender = () => {
    const items = ['男', '女'];
    uni.showActionSheet({
      itemList: items,
      success: async (res) => {
        const selectedGender = res.tapIndex + 1; // 1=男, 2=女
        state.model.sex = selectedGender;
        await saveUserInfo();
      }
    });
  };

  // 选择微信的头像，进行上传
  async function onChooseAvatar(e) {
    const tempUrl = e.detail.avatarUrl || '';
    if (!tempUrl) return;
    const files = await uploadFilesFromPath(tempUrl);
    if (files.length > 0) {
      state.model.avatar = files[0].url;
      await saveUserInfo();
    }
  }

  // 手动选择头像，进行上传
  async function onChangeAvatar() {
    const files = await chooseAndUploadFile({ type: 'image' });
    if (files.length > 0) {
      state.model.avatar = files[0].url;
      await saveUserInfo();
    }
  }

  // 保存用户信息
  const saveUserInfo = async () => {
    try {
      const { code } = await UserApi.updateUser({
        avatar: state.model.avatar,
        nickname: state.model.nickname,
        sex: state.model.sex,
      });
      if (code === 0) {
        await getUserInfo();
        uni.showToast({
          title: '保存成功',
          icon: 'success'
        });
      }
    } catch (error) {
      console.error('保存用户信息失败:', error);
      uni.showToast({
        title: '保存失败',
        icon: 'none'
      });
    }
  };

  // 获得用户信息
  const getUserInfo = async () => {
    // 个人信息
    const userInfo = await sheep.$store('user').getInfo();
    state.model = clone(userInfo);

    // 获得社交用户的信息
    if (sheep.$platform.name !== 'H5') {
      const result = await sheep.$platform.useProvider('wechat').getInfo();
      state.thirdInfo = result || {};
    }
  };

  onBeforeMount(() => {
    getUserInfo();
  });
</script>

<style lang="scss" scoped>
.profile-page {
  min-height: 100vh;
  background: #f5f5f5;
}

// 头像区域
.avatar-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 60rpx 0 60rpx;
  background: #fff;
  
  .avatar-container {
    position: relative;
    width: 200rpx;
    height: 200rpx;
    margin-bottom: 20rpx;
    
    .avatar-image {
      width: 100%;
      height: 100%;
      border-radius: 50%;
      border: 4rpx solid #fff;
      box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
    }
    
    .camera-icon {
      position: absolute;
      bottom: -10rpx;
      right: -10rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      
      .camera-image {
        width: 80rpx;
        height: 80rpx;
      }
    }
  }
  
  .upload-hint {
    font-size: 24rpx;
    color: #999;
  }
}

// 个人信息卡片
.info-card {
  background: #fff;
  margin: 20rpx 30rpx;
  border-radius: 20rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  
  .info-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 40rpx 30rpx;
    border-bottom: 1rpx solid #f5f5f5;
    
    &:last-child {
      border-bottom: none;
    }
    
    .info-label {
      font-size: 28rpx;
      color: #333;
      font-weight: 600;
    }
    
    .info-content {
      display: flex;
      align-items: center;
      gap: 20rpx;
      
      .info-value {
        font-size: 28rpx;
        color: #666;
      }
      
      .arrow-icon {
        font-size: 32rpx;
        color: #ccc;
        font-weight: bold;
      }
    }
  }
}

// 修改昵称弹框
.nickname-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
  
  .modal-content {
    width: 600rpx;
    background: #fff;
    border-radius: 24rpx;
    overflow: hidden;
    
    .modal-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 40rpx 40rpx 30rpx;
      border-bottom: 1rpx solid #f5f5f5;
      
      .modal-title {
        font-size: 32rpx;
        font-weight: 600;
        color: #333;
      }
      
      .modal-close {
        width: 60rpx;
        height: 60rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 48rpx;
        color: #999;
        line-height: 1;
      }
    }
    
    .modal-body {
      padding: 40rpx;
      
      .nickname-input {
        width: 100%;
        height: 80rpx;
        padding: 0 20rpx;
        border: 2rpx solid #e5e5e5;
        border-radius: 12rpx;
        font-size: 28rpx;
        color: #333;
        background: #f9f9f9;
        box-sizing: border-box;
        
        &:focus {
          border-color: #B276FF;
          background: #fff;
        }
      }
    }
    
    .modal-footer {
      display: flex;
      border-top: 1rpx solid #f5f5f5;
      
      .modal-btn {
        flex: 1;
        height: 100rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 30rpx;
        
        &.cancel-btn {
          color: #666;
          border-right: 1rpx solid #f5f5f5;
        }
        
        &.confirm-btn {
          color: #B276FF;
          font-weight: 600;
        }
      }
    }
  }
}
</style>
